﻿using System.Globalization;
using System.Diagnostics;
namespace AnalyStock.DataManage;
internal static class CommAppMethod
{
    /// <summary>
    ///     提示信息方法通用处理,链式方法使用模式
    /// </summary>
    /// <param name="message"></param>
    public static void ErrorMessage(this string message)
    {
        MessageBox.Show(message, "错误提示", MessageBoxButton.OK, MessageBoxImage.Error);
    }

    public static void NotifyMessage(this string message)
    {
        MessageBox.Show(message, "完成提示", MessageBoxButton.OK, MessageBoxImage.Information);
    }

    public static bool IsConfirmMessage(this string strSuggestion)
    {
        return MessageBox.Show(strSuggestion, "确认操作",
            MessageBoxButton.OKCancel, MessageBoxImage.Question) is MessageBoxResult.OK;
    }

    ///
    ///一个可以捕捉异常架构，针对Async Void 返回类型
    ///
    public static async void WithCapturaException(this Task task)
    {
        try
        {
            await task;
        }
        catch (Exception ex)
        {
            ex.Message.ErrorMessage();
        }
    }
    public static async Task<IList<T>> WithCapturaException<T>(this Task<IList<T>> task) where T:class
    {
        try
        {
            return await task.ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            ex.Message.ErrorMessage();
        }
        return null;
    } 

    public static async ValueTask<T> WithCapturaException<T>(this Task<T> task) where T:struct
    {
        try
        {
            return await task.ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            ex.Message.ErrorMessage();
        }
        return default;
    }   

   /* public static async void  WithCapturaException(Func<Task> callback)
    {
         try
        {
          await callback?.Invoke();
        }
        catch (Exception ex)
        {
            ex.Message.ErrorMessage();
        }      
    } */   
    /// <summary>
    ///     可迭代集合NUll，Empty判断
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <returns></returns>
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) where T : class
    {
        return list is null || !list.Any(); // !list?.Any() ?? true;
    }
    /*public static bool IsNullThrowException<T>(this T t)
    {
        if (t == null)
        {
            return true;
            throw new ArgumentNullException($"{t} is null");
        }
        return false;
    }*/

    /// <summary>
    ///     手工清除已经填充、可放弃使用的集合数据，释放内存。该方法因系统内存管理机制存在质疑！
    /// </summary>
    /// <param name="list"></param>
    /// <typeparam name="T"></typeparam>
    public static void Dispose<T>(this ICollection<T> list)
    {
        list?.Clear();
    }

    /// <summary>
    ///     "yyyyMMdd"字符格式转换为日期格式；
    /// </summary>
    /// <param name="strDate"></param>
    /// <returns></returns>
    public static DateTime ConvertToDate(this string strDate)
    {
        return DateTime.ParseExact(
            strDate,
            "yyyyMMdd",
            CultureInfo.CurrentCulture
        );
        //return DateTime.Parse($"{strDate[0..4]}/{strDate[4..6]}/{strDate[6..8]}");
    }
    //转成常用日期格式"yyyyMMdd"
    public static string ToDateString(this DateTime date)
    {
        return date.ToString("yyyyMMdd");
    }
    //日期字符加分割符号"YYYY-MM-DD"
    public static string ToDateStrWithGapSymbols(this string date)
    {
        return string.Join("-", date[..4], date[4..6], date[6..8]);
    }

    /// <summary>
    ///     转换为只有四位小数位的浮点数
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static float ConvertToFourPoints(this float input)
    {
        return float.Round(input, 4);
    }

    public static float ConvertToFloat(this string input)
    {
        return string.IsNullOrWhiteSpace(input) ? 0.0f : Single.Parse(input);
    }

    /// <summary>
    /// 打开同花顺i问网页
    /// </summary>
    /// <param name="stockName"></param>
    public static void OpenNetByBrowser(string stockName)
    {
        stockName = stockName.Replace(" ", string.Empty);
        var defaultUri = "http://www.iwencai.com";
        var stockNameUri = $"http://www.iwencai.com/unifiedwap/result?w={stockName}";
        try
        {
            // 通过注册表找到浏览器安装路径
            var browserAppFileName = (string)
                ( Microsoft.Win32.Registry
                     .GetValue($"HKEY_LOCAL_MACHINE{ApplicationParam.NetBrowserAPPKey}", "", null)
                 ?? Microsoft.Win32.Registry
                     .GetValue($"HKEY_CURRENT_USER{ApplicationParam.NetBrowserAPPKey}", "", null));
            // 如果未找到浏览器则使用默认浏览器打开
            if (string.IsNullOrWhiteSpace(browserAppFileName))
            {
                Clipboard.SetDataObject(stockName);
                Process.Start("explorer.exe", defaultUri);
                return;
            }

            // 打开配置的浏览器
            Process.Start(browserAppFileName, stockNameUri);
        }
        catch (Exception ex)
        {
            ex.Message.ErrorMessage();
        }
    }
}

/// <summary>
/// 迭代集合扩展处理方法
/// </summary>
internal static class EnumerableExtension
{
    /// <summary>
    ///     同时获取集合的最大最小值
    /// </summary>    
    public static (TResult Max, TResult Min) MaxMinFloat<TSource, TResult>
        (this IEnumerable<TSource> source, Func<TSource, TResult> selector)
        where TResult : struct, IFloatingPoint<TResult>
    {
        ArgumentNullException.ThrowIfNull(source);
        ArgumentNullException.ThrowIfNull(selector);
        using var enumerator = source.GetEnumerator();
        if (!enumerator.MoveNext())
        {
            throw new NoNullAllowedException("the collection is empty...");
        }
        var val = selector(enumerator.Current);
        while (TResult.IsNaN(val))
        {
            if (!enumerator.MoveNext())
            {
                return (val, val);
            }
            val = selector(enumerator.Current);
        }
        TResult valMin = val, valMax = val;
        while (enumerator.MoveNext())
        {
            val = selector(enumerator.Current);
            if (TResult.IsNaN(val))
            {
                continue;
            }

            if (val > valMax)
            {
                valMax = val;
            }

            if (val < valMin)
            {
                valMin = val;
            }
        }
        return (valMax, valMin);
    }

    /// <summary>
    ///     集合内元素（此处元素一般为可迭代类型）,对集合元素逐一执行匿名方法。
    ///     链式形式代替ForEach语句，功能一样，方便语句编辑。
    /// </summary>
    /// <param name="source"></param>
    /// <param name="action"></param>
    /// <typeparam name="TSource"></typeparam>
    public static void ForEach<TSource>
        (this IEnumerable<TSource> source, Action<TSource> action)
    {
        ArgumentNullException.ThrowIfNull(source);
        using var enumerator = source.GetEnumerator();
        while (enumerator.MoveNext())
        {
            action(enumerator.Current);
        }
    }
}